<?php
declare(strict_types = 1);

namespace app\logic;

use app\ArrayToolkit;
use app\client\WeChatClient;
use app\logic\BaseLogic;
use app\model\SendMessageLog;
use think\facade\Db;

class Message extends BaseLogic
{
    protected $weChatClient = null;

    public function pushMessage($templateId, $userIds)
    {
        if (empty($templateId) || empty($userIds)) {
            $this->throwHttpException(500, '参数不全');
        }
        $template = $this->getTemplateLogic()->getTemplate($templateId);
        if (empty($template)) {
            $this->throwHttpException(500, '模版不存在');
        }


        $users = $this->getUserLogic()->findUserByIds($userIds);
        $userOpenIds = ArrayToolkit::column($users, 'wechat_open_id');
        $userOpenIds = array_map(function ($value) use ($templateId) {
            return $templateId.':'.$value;
        }, $userOpenIds);

        $this->getRedisCache()->lpush('send_message_queue', ...$userOpenIds);
    }

    public function pushMessageByTemplateId($templateId)
    {
        $users = $this->getUserLogic()->searchUsers(['wechat_open_id' != 0], [], 0, PHP_INT_MAX);
        $userIds = ArrayToolkit::column($users, 'id');
        $this->pushMessage($templateId, $userIds);
    }

    public function pushMessageCount()
    {
        return $this->getRedisCache()->lLen('send_message_queue');
    }

    /**
     * @return Template
     */
    protected function getTemplateLogic(): Template
    {
        return $this->getLogic('Template');
    }

    public function pushWeChate($templateId)
    {
        $userOpenId = $this->getRedisCache()->brpop('send_message_queue');

        $this->sendWeChatMessage($templateId, $userOpenId);
    }

    public function sendWeChatMessage($templateId, $userOpenId)
    {
        $template = $this->getRedisCache()->get('template:'.$templateId);
        if (empty($template)) {
            $template = $this->getTemplateLogic()->getTemplate($templateId);
            $this->getRedisCache()->set('template:'.$templateId, $template);
        }

        $data = $this->buildMessageData($template, $userOpenId);

        $result = $this->getWeChatClient()->pushMessage($data);
        $this->getRedisCache()->lpush('send_log_queue', $templateId.':'.$userOpenId);

        return $result;
    }

    public function buildMessageData($template, $userOpenId)
    {
        if (empty($template['data'])) {
            return [];
        }
        $messageData = [
            'touser' => $userOpenId,
            'template_id' => $template['template_id'],
        ];

        $data = json_decode($template['data'], true);
        foreach ($data as $key => $selectFields) {
            if ($selectFields == 'current_time') {
                $messageData['data'][$key]['value'] = date('Y-m-d H:i:s');
                $messageData['data'][$key]['color'] = '#173177';
                continue;
            }

            $array = explode('.', $selectFields);
            if ($array[0] == 'input') {
                unset($array[0]);
                $messageData['data'][$key]['value'] = implode('.', $array);
                $messageData['data'][$key]['color'] = '#173177';
                continue;
            }

            $select = explode('-', $array[2]);
            $result = $this->getLogic(ucfirst($array[0]))->getByFields($select[1], $select[2] ?? $userOpenId);
            if (!empty($result)) {
                $messageData['data'][$key]['value'] = $result[$array[1]];
                $messageData['data'][$key]['color'] = '#173177';
            }
            unset($result);
        }

        return $messageData;
    }

    /**
     * @return User
     */
    protected function getUserLogic(): User
    {
        return $this->getLogic('User');
    }

    /**
     * @return WeChatClient|null
     */
    protected function getWeChatClient(): ?WeChatClient
    {
        if (empty($this->weChatClient)) {
            $wechat = config('wechat');
            return new WeChatClient($wechat['wechat_app_id'], $wechat['wechat_app_secret']);
        }

        return $this->weChatClient;
    }
}
